/**
 * DataAccessObject.java
 * 
 * Created on 21.05.2012 13:10:11
 */
package de.g18.scavengerhunt.types;

import java.util.HashMap;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * This is a wrapper to map all request to the underlying sqLite database
 */
public class DatabaseAdapter {

    private static final String TAG                = "DatabaseHelper";

    private static final String DATABASE_NAME      = "ScavengerHunt";

    private static final int    DB_VERSION         = 1;

    private static final String TABLE_CONF         = "configuration";

    private static final String CONF_USER_NAME     = "username";

    private static final String CONF_USER_ID       = "userid";

    private static final String CONF_ENCODED_IMAGE = "profileImage";

    private SQLiteDatabase      database           = null;

    private DatabaseHelper      databaseHelper     = null;

    public DatabaseAdapter(Context context) {
        databaseHelper = new DatabaseHelper(context);
    }


    public boolean open() {
        database = databaseHelper.getWritableDatabase();
        if (database == null) {
            return false;
        } else {
            return true;
        }
    }

    public void close() {
        databaseHelper.close();
        database = null;
    }

    public void setUserId(int userId) {
        if (database == null)
            open();
        StringBuilder builder = new StringBuilder();
        builder.append("UPDATE ").append(TABLE_CONF).append(" SET ").append(CONF_USER_ID).append("=").append(userId);
        database.execSQL(builder.toString());
        close();
    }

    public int getUserId() {
        if (database == null) {
            open();
        }
        int retValue = 0;
        String[] columns = {CONF_USER_ID};
        Cursor cursor = database.query(true, TABLE_CONF, columns, null, null, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            retValue = cursor.getInt(0);
        }
        close();
        return retValue;
    }

    public String getUserName() {
        return getStringValueFromTable(CONF_USER_NAME);
    }

    public void setUserName(String username) {
        setStringValue(CONF_USER_NAME, username);
    }

    public String getEncodedImage() {
        return getStringValueFromTable(CONF_ENCODED_IMAGE);
    }

    public void setEncodedImage(String encodedImage) {
        System.out.println("encodedImage.length() = " + encodedImage.length());
        setStringValue(CONF_ENCODED_IMAGE, encodedImage);
    }

    private void setStringValue(String fieldName, String value) {
        if (database == null) {
            open();
        }
        StringBuilder builder = new StringBuilder();
        builder.append("UPDATE ").append(TABLE_CONF).append(" SET ").append(fieldName).append("='").append(value).append("'");
        database.execSQL(builder.toString());
        close();
    }

    private String getStringValueFromTable(String fieldName) {
        if (database == null) {
            open();
        }
        String retValue = null;
        String[] columns = {fieldName};
        Cursor cursor = database.query(TABLE_CONF, columns, null, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            retValue = cursor.getString(0);
        }
        close();
        return retValue;
    }

    /**
     * Some database stuff to make main class easier to read
     */
    private class DatabaseHelper extends SQLiteOpenHelper {
        
        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DB_VERSION);
        }
        
        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.d(TAG, "Creating table " + TABLE_CONF);
            StringBuilder builder = new StringBuilder();
            builder.append("CREATE TABLE IF NOT EXISTS ").append(TABLE_CONF).append("(").append(CONF_USER_ID).append(" INT(11) NOT NULL, ").append(CONF_USER_NAME).append(" VARCHAR(255) NOT NULL, ")
            .append(CONF_ENCODED_IMAGE).append(" TEXT NOT NULL)");
            db.execSQL(builder.toString());
            
            Map<String, String> map = new HashMap<String, String>();
            map.put(CONF_USER_ID, "0");
            map.put(CONF_USER_NAME, "default");
            map.put(CONF_ENCODED_IMAGE, "");
            insertData(map, db);
        }
        
        
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.d(TAG, "Upgrading database");
            
            String userName = getUserName();
            int userId = getUserId();
            String profileImage = getEncodedImage();
            
            // Drop older table if existed
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONF);
            
            // Create tables again
            onCreate(db);
            
            Map<String, String> map = new HashMap<String, String>();
            map.put(CONF_USER_ID, String.valueOf(userId));
            map.put(CONF_USER_NAME, userName);
            map.put(CONF_ENCODED_IMAGE, profileImage);
            insertData(map, db);
        }
        
        private void insertData(Map<String, String> dataMap, SQLiteDatabase db) {
            Log.d(TAG, "Inserting configuration data");
            ContentValues contentValues = new ContentValues();
            for (String key : dataMap.keySet()) {
                contentValues.put(key, dataMap.get(key));
            }
            db.insert(TABLE_CONF, null, contentValues);
        }
    }
}
